<script setup lang="ts">
import { h, ref, reactive, watch } from 'vue'
import { NModal, NCard, NForm, NSpace, NFormItem, NInput, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst } from 'naive-ui'

import { useDictStore } from '@/stores/dictStore'
import http from '@/tools/http'
import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()
const props = defineProps(['dictCode'])

watch(() => props.dictCode, (dictCode) => {
    dictItemSearchFormValue.dictCode = dictCode
    formData.dictCode = dictCode
    pageDictItem()
})

type RowData = {
    dictCode?: string
    dictItemName?: string
    dictItemValue?: string
    remark?: string
}

const dictItemTableColumns: any = [
    {
        title: "字典编码",
        key: "dictCode",
        width: 200,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "字典项名称",
        key: "dictItemName",
        width: 120,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "字典项值",
        key: "dictItemValue",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "备注",
        key: "remark",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作",
        key: "actions",
        width: 132,
        fixed: 'right',
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    userStore.hasAuth("dict:edit") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openEditDictItem(rowData)
                        },
                        { default: () => "编辑" }
                    ) : null,
                    userStore.hasAuth("dict:delete") ? h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteDictItem()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteDictItem(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除该字典项？" }
                        }
                    ) : null
                ]
            )
        }
    }
]

const dictData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const dictItemSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    dictCode: null,
    dictItemName: null,
    dictItemValue: null
})

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    dictCode: undefined,
    dictItemName: "",
    dictItemValue: "",
    remark: ""
})

const formRules = {
    dictCode: {
        required: true,
        message: '请输入字典值',
        trigger: ['input']
    },
    dictItemName: {
        required: true,
        message: '请输入字典项名称',
        trigger: ['input']
    },
    dictItemValue: {
        required: true,
        message: '请输入字典项值',
        trigger: ['input']
    }
}


const dictStore = useDictStore()

function pageNumChange(pageNum: number) {
    dictItemSearchFormValue.pageNum = pageNum
    pageDictItem()
}

function pageSizeChange(pageSize: number) {
    dictItemSearchFormValue.pageSize = pageSize
    pageDictItem()
}

let currentRow = ref<number>(-1)

function dataTableRowClicked(rowData: RowData, rowIndex: number) {
    return {
        style: 'cursor: pointer;',
        onClick: () => {
            if (currentRow.value !== rowIndex) {
                currentRow.value = rowIndex
            }
        }
    }
}

function updateRowClassName(rowData: RowData, rowIndex: number) {
    if (currentRow.value === rowIndex) {
        return "selected"
    }
    return ""
}

function openAddDictItem() {
    visiable.value = true
    title.value = "添加字典项"
    formData.dictItemName = ""
    formData.dictItemValue = ""
    formData.remark = ""
}

function openEditDictItem(row: any) {
    visiable.value = true
    title.value = "编辑字典项"
    formData.dictItemName = row.dictItemName
    formData.dictItemValue = row.dictItemValue
    formData.remark = row.remark
}

function openDeleteDictItem(row: any) {
    formData.dictItemName = row.dictItemName
    formData.dictItemValue = row.dictItemValue
    formData.remark = row.remark
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (title.value === "添加字典项") {
                addDictItem()
            } else {
                updateDictItem()
            }
            visiable.value = false
        }
    })
}

function pageDictItem() {
    http.post("/dictionary/item/page", dictItemSearchFormValue).then(({ data }) => {
        dictData.pageNum = data.data.pageNum
        dictData.pageSize = data.data.pageSize
        dictData.pages = data.data.pages
        dictData.total = data.data.total
        dictData.list.length = 0
        for (let i = 0; i < data.data.list.length; i++) {
            dictData.list.push(data.data.list[i])
        }
    })
}

const notification = useNotification()

function addDictItem() {
    http.post("/dictionary/item/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDictItem()
            dictStore.refresh()
        }
    })
}

function updateDictItem() {
    http.post("/dictionary/item/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDictItem()
            dictStore.refresh()
        }
    })
}

function deleteDictItem() {
    http.post("/dictionary/item/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDictItem()
            dictStore.refresh()
        }
    })
}
</script>

<template>
    <div class="search" style="margin-left:6px;">
        <n-form :model="dictItemSearchFormValue" inline label-placement="left">
            <n-form-item label="字典项名称" path="dictItemName">
                <n-input v-model:value="dictItemSearchFormValue.dictItemName" placeholder="请输入字典项名称" clearable />
            </n-form-item>
            <n-form-item label="字典项值" path="dictItemValue">
                <n-input v-model:value="dictItemSearchFormValue.dictItemValue" placeholder="请输入字典项值" clearable />
            </n-form-item>
            <n-form-item>
                <div class="display-flex-end">
                    <n-button attr-type="button" @click="pageDictItem()">查询</n-button>
                </div>
            </n-form-item>
        </n-form>
    </div>
    <div class="btn-group" style="margin-left:6px;">
        <n-button v-if="userStore.hasAuth('dict:add')" attr-type="button" @click="openAddDictItem()"
            :disabled="!formData.dictCode">新增</n-button>
    </div>
    <div class="data-table" style="margin-left:6px;">
        <n-data-table :scroll-x="632" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
            :row-class-name="updateRowClassName" :row-props="dataTableRowClicked" :columns="dictItemTableColumns"
            :data="dictData.list" :bordered="false" />
    </div>
    <div class="pagination" style="margin-left:6px;">
        <n-pagination style="float:right" v-model:page="dictData.pageNum" :page-size="dictData.pageSize"
            :item-count="dictData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
            :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 400px" :title="title">
            <n-form ref="formRef" :model="formData" :rules="formRules" label-width="92px" label-placement="left"
                require-mark-placement="left">
                <n-form-item label="字典编码" path="dictCode">
                    <n-input v-model:value="formData.dictCode" :disabled="true" placeholder="请输入字典编码" />
                </n-form-item>
                <n-form-item label="字典项名称" path="dictItemName">
                    <n-input v-model:value="formData.dictItemName" placeholder="请输入字典项名称" />
                </n-form-item>
                <n-form-item label="字典项值" path="dictItemValue">
                    <n-input v-model:value="formData.dictItemValue" :disabled="title === '编辑字典项'" placeholder="请输入字典项值" />
                </n-form-item>
                <n-form-item label="备注" path="remark">
                    <n-input v-model:value="formData.remark" placeholder="请输入备注" />
                </n-form-item>
            </n-form>
            <template #footer>
                <div class="display-flex-end">
                    <n-space>
                        <n-button attr-type="button" @click="visiable = false">取消</n-button>
                        <n-button attr-type="button" @click="submit()">提交</n-button>
                    </n-space>
                </div>
            </template>
        </n-card>
    </n-modal>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>